import common from "../../../utils/common";

const app = getApp()
const ip = app.globalData.ipStr
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 获取导航栏信息
        // 导航栏的高度 = 状态栏高度 + 胶囊高度 +（胶囊top - 状态栏高度）* 2 
        dhlTop: app.globalData.dhlTop,
        dhlHeight: app.globalData.dhlHeight,
        windowHeight: app.globalData.windowHeight,

        avatarUrl: '',
        defaultAvatarUrl: defaultAvatarUrl,

        nickName: '微信用户',
        activeSexVal: '',
        wxno: '',
        phone: '',
        refer: '',



        sexOptionArr: [
            { value: '1', text: '男' },
            { value: '0', text: '女' },
        ],

        personalMarkOptionArr: [
            { value: '小白', text: '小白', check: false },
            { value: '铲屎官', text: '铲屎官', check: false },
            { value: '学生', text: '学生', check: false },
            { value: '土著', text: '土著', check: false },
        ],
        showPopover: false,
        customMark: '',

    },

    /**
     * 加载时获取用户信息
     * 
     */
    getUserInfoVO() {
        // wx.showLoading({
        //     title: '加载中...',
        // })

        // 请求后端 
        wx.request({
            url: 'http://' + ip + '/weixin/getUserInfoVO',
            method: 'POST',
            header: {
                'Authorization': wx.getStorageSync("token"),
                'content-type': 'application/json;charset=UTF-8'
            },
            // data: { size: this.data.size, current: tempCurrent },
            success: res => {
                const userData = res.data.data
                console.info('用户详情返回信息=' + JSON.stringify(userData))
                if (res.statusCode == 200) {
                    common.new_p(userData.avatarUrl).then((res) => {
                        this.setData({ avatarUrl: res })
                    })

                    this.setData({ nickName: userData.nickName, wxno: userData.wxno, phone: userData.phone, refer: userData.refer, activeSexVal: userData.gender, personalMarkOptionArr: userData.markArr });
                }
            },
            fail: e => {
                console.info('用户详情异常返回信息=' + JSON.stringify(e))
            },
            complete: c => {
                // wx.hideLoading()
            }
        })
    },

    /**
     * 点击保存按钮
     * 保存或修改用户信息
     * @param {保存按钮} e 
     */
    clickSaveUserInfo(e) {
        // 上传头像 todo
        // avatarUrl: '',
        // markSelectLabelValArr: [],
        // 校验数据
        var nickName = this.data.nickName
        if (nickName.length == 0) {
            wx.showToast({
                title: '请输入昵称，用于展示',
                icon: 'none',
                duration: 1500
            })
            return false;
        }

        var gender = this.data.activeSexVal
        if(gender == ''){
            wx.showToast({
                title: '请选择性别',
                icon: 'none',
                duration: 1500
            });
            return false;
        }

        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
        var phoneMobile = this.data.phone
        if (phoneMobile.length === 0) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none',
                duration: 1500
            });
            return false;
        } else if (phoneMobile.length < 11) {
            wx.showToast({
                title: '手机号长度有误！',
                icon: 'none',
                duration: 1500
            });
            return false;
        } else if (!myreg.test(phoneMobile)) {
            wx.showToast({
                title: '手机号有误！',
                icon: 'none',
                duration: 1500
            });
            return false;
        }
        var userSaveParam = { nickName: this.data.nickName, gender:gender, phone: phoneMobile, wxno: this.data.wxno, refer: this.data.refer, markArr: this.data.personalMarkOptionArr };

        wx.request({
            url: 'http://' + ip + '/weixin/saveUserInfo',
            method: 'POST',
            header: {
                'Authorization': wx.getStorageSync("token"),
                'content-type': 'application/json;charset=UTF-8'
            },
            data: userSaveParam,
            success: res => { //wx.request成功的回调
                console.info('保存用户信息返回信息=' + JSON.stringify(res))
                if (res.statusCode == 200) {
                    const avatarUrl = this.data.avatarUrl;
                    new Promise((resolve, reject) => {
                        wx.uploadFile({
                            filePath: avatarUrl,
                            name: 'file',
                            url: 'http://' + ip + '/house-img/upload',
                            header: {
                                'Authorization': wx.getStorageSync("token"),
                                "Content-Type": "multipart/form-data"
                            },
                            formData: {
                                kind: 0  // 看调用场景赋值 图片类型：1 首图、2普通房图、头像 0
                            },
                            dataType: 'json',
                            success(res) { resolve(avatarUrl + '上传头像成功,返回结果：' + JSON.stringify(res)) },
                            fail(e) { reject(new Error(avatarUrl + '上传头像失败，' + JSON.stringify(e))) }
                        })
                    }).then(result => {
                        console.log(result);
                        wx.showToast({
                            title: '保存成功',
                            icon: 'success',
                            duration: 2000,
                            complete: function () {
                                wx.navigateBack({
                                    delta: 1,
                                    success: function (e) {
                                    }
                                });
                            }
                        })
                    })
                        .catch(error => {
                            console.error(error);
                            // 处理 Promise 对象被拒绝的情况
                        });;
                }
            }
        })
    },

    showMarkView(e) {
        this.setData({ showPopover: true })
    },
    /**
    * 选择个人标签
    * @param {个人标签} e 
    */
    clickPersonalMark: function (e) {
        const subItem = e.currentTarget.dataset.item
        var checkFlag = subItem.check;
        var personalMarkOptionArr = this.data.personalMarkOptionArr
        var markSelectLabelArr = []
        var markSelectLabelValArr = []
        // 多选点击
        common.multiGroupClickVal(markSelectLabelArr, markSelectLabelValArr, personalMarkOptionArr, checkFlag, subItem.value)
        this.setData({
            personalMarkOptionArr
        })
    },
    submit(e) {
        var customMark = this.data.customMark
        var personalMarkOptionArr = this.data.personalMarkOptionArr
        var tempMark = { value: personalMarkOptionArr.length, text: customMark, check: false };
        personalMarkOptionArr.push(tempMark)
        this.setData({ showPopover: false, customMark: '', personalMarkOptionArr })
    },
    close(e) {
        console.info('close')
        this.setData({ showPopover: false, customMark: '' })
    },
    sexRadioChange(e) {
        console.log('radio发生change事件，携带value值为：', e.detail.value)
        // const sexOptionArr = this.data.sexOptionArr
        // for (let i = 0, len = sexOptionArr.length; i < len; ++i) {
        //     sexOptionArr[i].check = sexOptionArr[i].value === e.detail.value
        // }
        this.setData({
            activeSexVal: e.detail.value
        })
    },

    /**
     * 选择微信头像
     * @param {微信头像} e 
     */
    onChooseAvatar(e) {
        console.log(e, 'e')
        let avatarUrl = e.detail.avatarUrl
        if (avatarUrl) {
            this.setData({ avatarUrl: avatarUrl })
        }
    },
    pickerChange: function (e) {
        this.doSetData(e.currentTarget.dataset.atr, e.detail.value)
    },

    doSetData: function (vari, val) { this.setData({ [vari]: val }) },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getUserInfoVO();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
})